package middleware

import (
	"api/controller"
	jwt_tool "api/tool/jwt"
	"net/http"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func Login() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Token")
		if token == "" {
			controller.ResultError(http.StatusUnauthorized, controller.UNAUTHORIZED, controller.Msg[controller.UNAUTHORIZED], c)
			c.Abort()
			return
		}
		mc, err := jwt_tool.ParseToken(token)
		if err != nil {
			v, _ := err.(*jwt.ValidationError)
			if v.Errors == jwt.ValidationErrorExpired {
				controller.ResultError(http.StatusUnauthorized, controller.TOKENTIMEOUTERROR, controller.Msg[controller.TOKENTIMEOUTERROR], c)
			} else {
				controller.ResultError(http.StatusUnauthorized, controller.UNAUTHORIZED, controller.Msg[controller.UNAUTHORIZED], c)
			}
			c.Abort()
			return
		}
		c.Set("id", mc.Id)
		c.Set("username", mc.Username)
		c.Set("role", mc.Role)
		c.Next()
	}
}
